% File SegFood.m
function [R,E,J] = SegFood(I,p)
J = rgb2hcm(double(I)/256);
t = graythresh(J);
if ~exist('p','var')
    p = -0.05;
end
[R,E] = MorphoFood(J,t+p);
end

% File rgb2hcm.m
function J = rgb2hcm(RGB)
if size(RGB,3)==1
    I = RGB;
else
    RGB64 = imresize(RGB,[64 64]);
    k = fminsearch(@(k) StdMonochrome(k,RGB64),[1 1]);
    I = k(1)*RGB(:,:,1) + k(2)*RGB(:,:,2) + RGB(:,:,3);
end
J = (I - min(I(:)))/(max(I(:)) - min(I(:)));
n = fix(size(J,1)/4);
if mean2(J(1:n,1:n))>0.3
    J = 1-J;
end
end

% File StdMonochrome
function s = StdMonochrome(k,RGB)
I = k(1)*RGB(:,:,1) + k(2)*RGB(:,:,2) + RGB(:,:,3);
s = -std2(I)/(max(I(:))-min(I(:)));
end

% File MorphoFood.m
function [R,E] = MorphoFood(J,t)
A = bwareaopen(J>t,fix(numel(J)/1000));
C = imclose(double(A),strel('disk',7));
R = bwfill(C,'holes',8);
E = bwperim(R,4);
end


